import 'package:cbec_app/components/decoration/DecorationRedPacket/red_packet_Item_entity.dart';
import 'package:get/get.dart';

import '../../../entity/home/content/red_packet_decoration_entity.dart';
import '../../../utils/Tools.dart';
import '../../http/network.dart';

class DecorationRedPacketCtr extends GetxController {
  var dataList = <RedPacketItemEntity?>[].obs; // 存储返回的列表数据
  void fetchRedPacketData(RedPacketDecorationEntity model) {
    print('红包配置===$model');
    List<String>? marketingIds = model.redPacket!.map((item) => item.marketingId!).toList();
    Map<String, dynamic> params = {};
    params['marketingIds'] = marketingIds;
    fetchData(params);
  }

  void fetchData(Map<String, dynamic> params) {
    Network.automaticGainRedPacketList(params).then((value) {
      print('红包列表===$value');
      var tempList = (value as List<dynamic>).map((item) => RedPacketItemEntity.fromJson(item as Map<String, dynamic>)).toList();
      dataList.assignAll(tempList);
    }).catchError((error) {});
  }

  ///领取红包
  void receiveRedPack(String redPacketId) async {
    await Network.receiveRedPack(redPacketId);
    Tools.showToast('领取成功');
    RedPacketItemEntity? redPacket = dataList.firstWhere(
      (item) => item?.marketingId == redPacketId,
      orElse: () => null, // 返回 null 是允许的，前提是 redPacket 类型可以为 null
    );

    if (redPacket != null) {
      redPacket.hasGet = 1;
      dataList.refresh();
    }
  }
}
